package com.techwells.learningkites.fragment;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.bitmap.core.BitmapSize;
import com.techwells.learningkites.R;
import com.techwells.learningkites.R.drawable;
import com.techwells.learningkites.R.id;
import com.techwells.learningkites.adapter.VideoGridAdapter;
import com.techwells.learningkites.adapter.VideoListAdapter;
import com.techwells.learningkites.adapter.VideoViewPagerAdapter;
import com.techwells.learningkites.controller.MainPageActivity;
import com.techwells.learningkites.controller.VideoDetailActivity;
import com.techwells.learningkites.model.MainPageViewModel;
import com.techwells.learningkites.networkaccess.KitesRequestUrl;
import com.techwells.learningkites.networkservice.KitesServiceMediator;
import com.techwells.learningkites.networkservice.model.Page;
import com.techwells.learningkites.networkservice.model.VideoCategory;
import com.techwells.taco.mvvm.Route;
import com.techwells.taco.tasktool.TaskToken;
import com.techwells.taco.widget.HorizontalListView;

import android.R.integer;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.SimpleAdapter;

public class VideoFragment extends Fragment implements OnItemClickListener, OnCheckedChangeListener, OnClickListener {
	private RadioGroup rgVideo;
	private int[] rbs = {R.drawable.selector_movie ,R.drawable.selector_speech ,R.drawable.selector_pub_class ,
			R.drawable.selector_news ,R.drawable.selector_sport};
	private String[] rbtext = {"电影","演讲","公开课","新闻","体育"};
	
	private ViewPager vpVideo;
	private List<View> vpViews;
	private View view;
	private VideoViewPagerAdapter adapter;
	
	private GridView gridVideo;
	private List<Map<String, Object>> listVideo;
	private SimpleAdapter simpleAdapter;
	
	private List<VideoCategory> videoCategoryList;
	private MainPageActivity activity;
	private BitmapUtils bitmapUtils;
	private BitmapDisplayConfig bitmapDisplayConfig;
	private int pageCount;
	private int pageNum;
	private Page page;
	private List<Page> pageList;
	
//	private HorizontalListView lvVideo;
//	private VideoListAdapter videoAdapter;
	
	private ImageView videoImg1,videoImg2,videoImg3,videoImg4;
	private TextView videoTxt1,videoTxt2,videoTxt3,videoTxt4;
	private VideoGridAdapter videoAdapter;
	
	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_video, container,false);
	}

	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		activity = (MainPageActivity) getActivity();
		initViews();
		initViewPager();
		
	}

	private void initGridViews() {
		gridVideo =  (GridView) view.findViewById(R.id.gv_video);
		listVideo = new ArrayList<Map<String,Object>>();
		for(int i=0;i<9;i++)  
	      {  
	        HashMap<String, Object> map = new HashMap<String, Object>();  
	        map.put("ItemImage", R.drawable.video_demo);
	        map.put("ItemText", "超凡蜘蛛精"); 
	        listVideo.add(map);  
	      }
		simpleAdapter = new SimpleAdapter(getActivity(), listVideo, R.layout.item_videolist, 
				new String[]{"ItemImage","ItemText"}, new int[]{R.id.item_image,R.id.item_text});
		gridVideo.setAdapter(simpleAdapter);
		gridVideo.setOnItemClickListener(this);
		
	}

	private void initViewPager() {
		vpVideo = (ViewPager) getActivity().findViewById(R.id.vp_video);
		vpViews = new ArrayList<View>();
////		for (int i = 0; i < rgVideo.getChildCount(); i++) {
//		for (int i = 0; i < 4; i++) {
//			view = getActivity().getLayoutInflater().inflate(
//					R.layout.viewpager_video, null);
//			initGridViews();
//			vpViews.add(view);
//		}
//		adapter = new VideoViewPagerAdapter(getActivity(), vpViews);
//		vpVideo.setAdapter(adapter);
//		
//		vpVideo.setCurrentItem(0);
//		vpVideo.setOffscreenPageLimit(3);
//		vpVideo.setOnPageChangeListener(new OnPageChangeListener() {
//			
//			@Override
//			public void onPageSelected(int arg0) {
////					RadioButton rb = (RadioButton) rgVideo.getChildAt(arg0);
////					rb.setChecked(true);
//				setVideoTextColor(arg0);
//			}
//			
//			@Override
//			public void onPageScrolled(int arg0, float arg1, int arg2) {
//				// TODO Auto-generated method stub
//				
//			}
//			
//			@Override
//			public void onPageScrollStateChanged(int arg0) {
//				// TODO Auto-generated method stub
//				
//			}
//		});
		
	}

	private void initViews() {
//		rgVideo = (RadioGroup) getActivity().findViewById(R.id.rg_video);
		
//		for (int i = 0; i < 5; i++) {
//			RadioButton rb = new RadioButton(getActivity());
//			rb.setPadding(20, 10, 20, 10);
//			//去掉默认的button
//			rb.setButtonDrawable(android.R.color.transparent);
//			//设置DrawableTop的图片
//			rb.setCompoundDrawablesWithIntrinsicBounds(0, rbs[i], 0, 0);
//			rb.setText(rbtext[i]);
//			rb.setTextColor(getResources().getColor(R.color.white));
//			rb.setTextSize(14);
//			rb.setGravity(Gravity.CENTER_HORIZONTAL);
//			rgVideo.addView(rb);
//			if (i == 0) {
//				rb.setChecked(true);
//			}
//		}
		
//		rgVideo.setOnCheckedChangeListener(this);
		
//		lvVideo = (HorizontalListView) getActivity().findViewById(R.id.lv_video);
		videoImg1 = (ImageView) getActivity().findViewById(R.id.img_1);
		videoImg2 = (ImageView) getActivity().findViewById(R.id.img_2);
		videoImg3 = (ImageView) getActivity().findViewById(R.id.img_3);
		videoImg4 = (ImageView) getActivity().findViewById(R.id.img_4);
		videoImg1.setOnClickListener(this);
		videoImg2.setOnClickListener(this);
		videoImg3.setOnClickListener(this);
		videoImg4.setOnClickListener(this);
		videoTxt1 = (TextView) getActivity().findViewById(R.id.name_1);
		videoTxt2 = (TextView) getActivity().findViewById(R.id.name_2);
		videoTxt3 = (TextView) getActivity().findViewById(R.id.name_3);
		videoTxt4 = (TextView) getActivity().findViewById(R.id.name_4);
		
	}

//	@Override
//	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
//		Route.route().nextController(getActivity(), VideoDetailActivity.class.getName(), Route.WITHOUT_RESULTCODE);
//	}
	
	
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		if ( pageList.size() != 0) {
			Intent intent = new Intent(getActivity(), VideoDetailActivity.class);
			intent.putExtra("videoId", pageList.get(vpVideo.getCurrentItem()).data.get(arg2).id);
			Route.route().nextControllerWithIntent(getActivity(), VideoDetailActivity.class.getName(), Route.WITHOUT_RESULTCODE,intent);
		}
		
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
//		for (int i = 0; i < rgVideo.getChildCount(); i++) {
//			if (checkedId == rgVideo.getChildAt(i).getId()) {
//				vpVideo.setCurrentItem(i);
//			}
//		}
//		
	}

	public void refreshData(TaskToken token) {
		
		String method = token.method;
		if (method.equals(KitesServiceMediator.SERVICE_GET_VIDEOS_CATEGORIES)) {
			videoCategoryList = ((MainPageViewModel)activity.baseViewModel).videoCategoryList;
//			videoAdapter = new VideoListAdapter(getActivity(), videoCategoryList);
//			lvVideo.setAdapter(videoAdapter);
//			lvVideo.setOnClickListener(this);
			
//			pageCount = videoCategoryList.size();
//			pageNum = 0;
//			if (pageCount > 0) {
//				doRequestGetCategoryVideos();
//			}
			
			for (int i = 0; i < videoCategoryList.size(); i++) {
				String string = videoCategoryList.get(i).name;
		        int index = string.indexOf("|");
		        videoCategoryList.get(i).name = string.substring(0,index);
			}
			
			bitmapDisplayConfig = new BitmapDisplayConfig();
			bitmapDisplayConfig.setShowOriginal(false);
			bitmapDisplayConfig.setBitmapMaxSize(new BitmapSize(50, 50));
			bitmapUtils = new BitmapUtils(getActivity());
			bitmapUtils.display(videoImg1, KitesRequestUrl.BASE_URL_IMG + videoCategoryList.get(0).icon);
			videoTxt1.setText(videoCategoryList.get(0).name);
			bitmapUtils.display(videoImg2, KitesRequestUrl.BASE_URL_IMG + videoCategoryList.get(0).icon);
			videoTxt2.setText(videoCategoryList.get(1).name);
			bitmapUtils.display(videoImg3, KitesRequestUrl.BASE_URL_IMG + videoCategoryList.get(0).icon);
			videoTxt3.setText(videoCategoryList.get(2).name);
			bitmapUtils.display(videoImg4, KitesRequestUrl.BASE_URL_IMG + videoCategoryList.get(0).icon);
			videoTxt4.setText(videoCategoryList.get(3).name);
			
			MainPageActivity.isRefresh ++;
			
			pageNum = 0;
			pageCount = videoCategoryList.size();
			pageList = new ArrayList<Page>();
			doRequestGetCategoryVideos(pageNum);
		}else if (method.equals(KitesServiceMediator.SERVICE_GET_CATEGORY_VIDEOS)) {
			page = ((MainPageViewModel)activity.baseViewModel).page;
			pageList.add(page);
			view = getActivity().getLayoutInflater().inflate(
					R.layout.viewpager_video, null);
			gridVideo =  (GridView) view.findViewById(R.id.gv_video);
			videoAdapter = new VideoGridAdapter(getActivity(), page.data);
			gridVideo.setAdapter(videoAdapter);
			gridVideo.setOnItemClickListener(this);
			vpViews.add(view);
			if (++pageNum < pageCount ) {
				doRequestGetCategoryVideos(pageNum);
			}else {
				adapter = new VideoViewPagerAdapter(getActivity(), vpViews);
				vpVideo.setAdapter(adapter);
				vpVideo.setCurrentItem(0);
				videoTxt1.setTextColor(getResources().getColor(R.color.blue_306));
				vpVideo.setOffscreenPageLimit(4);
				vpVideo.setOnPageChangeListener(new OnPageChangeListener() {
					
					@Override
					public void onPageSelected(int arg0) {
						setVideoTextColor(arg0);
					}
					
					@Override
					public void onPageScrolled(int arg0, float arg1, int arg2) {
						// TODO Auto-generated method stub
						
					}
					
					@Override
					public void onPageScrollStateChanged(int arg0) {
						// TODO Auto-generated method stub
						
					}
				});
				
			}
		}
		
		
	}

	private void doRequestGetCategoryVideos(int pageNum) {
		HashMap<String, Object> argMap = new HashMap<String, Object>();	
		argMap.put("categoryValue", videoCategoryList.get(pageNum).value);
		argMap.put("l", 20);
		argMap.put("n", 1);
		argMap.put("o", "id");
		argMap.put("s", "desc");
		activity.doTask(KitesServiceMediator.SERVICE_GET_CATEGORY_VIDEOS,argMap);
		
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.img_1:
			vpVideo.setCurrentItem(0);
			setVideoTextColor(0);
			break;
		case R.id.img_2:
			vpVideo.setCurrentItem(1);
			setVideoTextColor(1);
			break;
		case R.id.img_3:
			vpVideo.setCurrentItem(2);
			setVideoTextColor(2);
			break;
		case R.id.img_4:
			vpVideo.setCurrentItem(3);
			setVideoTextColor(3);
			break;

		default:
			break;
		}
		
	}

	private void setVideoTextColor(int i) {
		switch (i) {
		case 0:
			videoTxt1.setTextColor(getResources().getColor(R.color.blue_306));
			videoTxt2.setTextColor(getResources().getColor(R.color.white));
			videoTxt3.setTextColor(getResources().getColor(R.color.white));
			videoTxt4.setTextColor(getResources().getColor(R.color.white));
			break;
		case 1:
			videoTxt1.setTextColor(getResources().getColor(R.color.white));
			videoTxt2.setTextColor(getResources().getColor(R.color.blue_306));
			videoTxt3.setTextColor(getResources().getColor(R.color.white));
			videoTxt4.setTextColor(getResources().getColor(R.color.white));
			break;
		case 2:
			videoTxt1.setTextColor(getResources().getColor(R.color.white));
			videoTxt2.setTextColor(getResources().getColor(R.color.white));
			videoTxt3.setTextColor(getResources().getColor(R.color.blue_306));
			videoTxt4.setTextColor(getResources().getColor(R.color.white));
			break;
		case 3:
			videoTxt1.setTextColor(getResources().getColor(R.color.white));
			videoTxt2.setTextColor(getResources().getColor(R.color.white));
			videoTxt3.setTextColor(getResources().getColor(R.color.white));
			videoTxt4.setTextColor(getResources().getColor(R.color.blue_306));
			break;
		default:
			break;
		}
		
		
	}
	
	
	

}
